//
//  MineViewController.swift
//  V2ex-Swift
//
//  Created by Jasper on 2/28/16.
//  Copyright © 2016 Fin. All rights reserved.
//

import UIKit
import ImagePicker
import SVProgressHUD
import SDWebImage
import Kingfisher
import AVOSCloud

class MineViewController: RootViewController, UITableViewDelegate, UITableViewDataSource, ImagePickerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    struct cellItem {
        var name: String?
        var picName: String?
        var method: Selector?
        
    }
    
    @IBOutlet weak var tableView: UITableView!

//    let dataArray = ["我的发帖","我的回帖","去评分","清除缓存"]
    var dataArray:[cellItem]?
    var imagePickerController:ImagePickerController?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "我的"
        tabBarController?.tabBar.selectedItem?.selectedImage = UIImage(named: "tabbar_profile_selected")

        let fatieItem = cellItem(name: "我的主帖", picName: "fatie", method: #selector(MineViewController.goMyTopic))
        let huitieItem = cellItem(name: "我的回帖", picName: "huitie",method: #selector(MineViewController.goMyReply))
        let changeName = cellItem(name: "修改用户名", picName: "edit", method: #selector(MineViewController.goChangeName))
        let pingfenItem = cellItem(name: "给我们评分", picName: "ping_fen",method: #selector(MineViewController.rating))
        let qingchuItem = cellItem(name: "清除缓存", picName: "qingchu",method: #selector(MineViewController.clear))
        dataArray = [fatieItem,
                     huitieItem,
                     changeName,
                     pingfenItem,
                     qingchuItem]
        
        if AVUser.current() != nil {
            
        } else {
            
        }
    }
    
    func goMyTopic() {
        AVAnalytics.event("我的主贴")
        let myTopicVC = UIStoryboard.mainStoryboard.instantiateViewController(withIdentifier: "MyTopicViewController") as! MyTopicViewController;
        myTopicVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(myTopicVC, animated: true)
    }
    
    func goMyReply() {
        AVAnalytics.event("我的回帖")
        let myTopicVC = UIStoryboard.mainStoryboard.instantiateViewController(withIdentifier: "MyReplyViewController") as! MyReplyViewController;
        myTopicVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(myTopicVC, animated: true)
    }
    
    func goChangeName() {
        AVAnalytics.event("修改用户名")
        let myTopicVC = UIStoryboard.mainStoryboard.instantiateViewController(withIdentifier: "ChangeNameViewController") as! ChangeNameViewController;
        myTopicVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(myTopicVC, animated: true)
    }
    
    func clear() {
        AVAnalytics.event("清除缓存")
        AVFile.clearAllCachedFiles()
        SDImageCache.shared().cleanDisk()
        let cache = KingfisherManager.shared.cache
        cache.clearDiskCache()
        MineObjectHelper.removeCache()
        SVProgressHUD.showSuccess(withStatus: "清除成功！")
    }
    
    func rating() {
        AVAnalytics.event("评分")
//        let str = "itms-apps://itunes.apple.com/app/id1097808827"
        UIApplication.shared.openURL(URL.init(string: gaoloumiUrl)!)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tableView.reloadData()
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if AVUser.current() == nil {
            return 2
        }
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 1 {
            return dataArray!.count
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if (indexPath as NSIndexPath).section == 0 {
            return 90
        }
        return 44
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if (indexPath as NSIndexPath).section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MineTitleCell", for: indexPath) as! MineTitleCell
            cell.refreshView()
            return cell
        } else if (indexPath as NSIndexPath).section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MineSettingCell", for: indexPath) as! MineSettingCell
            let item = dataArray![(indexPath as NSIndexPath).row]
            cell.titleLabel.text = item.name
            cell.titeImageView.image = UIImage(named: item.picName!)
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MineLogoutCell", for: indexPath)
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        if AVUser.current() == nil && !(indexPath.section == 1 && indexPath.row >= 3) { // 此时一定只有两个section
            loginClick()
            return
        }
        
        if (indexPath as NSIndexPath).section == 0 {
    
            let alertController = UIAlertController(title: "", message: "更新资料", preferredStyle: .actionSheet)
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            let confirmAction = UIAlertAction(title: "更改头像", style: .destructive, handler: { (action) in
//                if self.imagePickerController == nil {
//                    self.imagePickerController = ImagePickerController()
//                    self.imagePickerController?.delegate = self
//                    self.imagePickerController?.imageLimit = 1
//                }
//                dispatch_async(dispatch_get_main_queue(), {
//                    self.presentViewController(self.imagePickerController!, animated: true, completion: nil)
//                })
                
                let subAlertController = UIAlertController(title: "", message: "请选择文件来源", preferredStyle: .actionSheet)
                let subCancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
                let cameraAction = UIAlertAction(title: "照相机", style: .destructive, handler: { (action) in
                    
                    let imagePicker = UIImagePickerController()
                    imagePicker.delegate = self
                    imagePicker.allowsEditing = true
                    imagePicker.sourceType = .camera
                    
                    
                    self.present(imagePicker, animated: true, completion: {})
                })
                let libraryAction = UIAlertAction(title: "本地相册", style: .destructive, handler: { (action) in
                    let imagePicker = UIImagePickerController()
                    imagePicker.delegate = self
                    imagePicker.allowsEditing = true
                    imagePicker.sourceType = .photoLibrary
                    
                    self.present(imagePicker, animated: true, completion: {})
                })
                subAlertController.addAction(subCancelAction)
                subAlertController.addAction(cameraAction)
                subAlertController.addAction(libraryAction)
                self.present(subAlertController, animated: true, completion: nil)
                
            })
            alertController.addAction(cancelAction)
            alertController.addAction(confirmAction)
            self.present(alertController, animated: true, completion: nil)
            
        } else if (indexPath as NSIndexPath).section == 1 {
            let item = dataArray![(indexPath as NSIndexPath).row]
            let sel = item.method
            self.perform(sel!)
        } else {
            let alertController = UIAlertController(title: "", message: "确定要退出登陆吗？", preferredStyle: .actionSheet)
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            let confirmAction = UIAlertAction(title: "退出登陆", style: .destructive, handler: { (action) in
                AVAnalytics.event("退出登录")
                MineObjectHelper.logout()
                self.loginClick()
            })
            alertController.addAction(cancelAction)
            alertController.addAction(confirmAction)
            self.present(alertController, animated: true, completion: nil)
        }
    } 
    
    func loginClick() {
        let storyboard = UIStoryboard(name: "Main", bundle: nil);
        let loginViewController = storyboard.instantiateViewController(withIdentifier: "LoginViewController");
        loginViewController.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(loginViewController, animated: true)
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        segue.destination.hidesBottomBarWhenPushed = true
    }
    
    // MARK: ImagePickerDelegate
    func wrapperDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
        
    }
    func doneButtonDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
        imagePickerController?.dismiss(animated: true, completion: nil)
        SVProgressHUD.show(withStatus: "上传头像...")
        if images.count > 0 {
            //            let data = UIImagePNGRepresentation(images.first!)
            updateAvatar(images.first!)
        }
    }
    func cancelButtonDidPress(_ imagePicker: ImagePickerController) {
        
    }
    
    // 上传头像
    func updateAvatar(_ image: UIImage) {
        let data = UIImageJPEGRepresentation(image, 0.7)
        let file = AVFile(data: data!)
        SVProgressHUD.show(withStatus: "正在上传头像...")
        file.saveInBackground({ (succeed: Bool, error: Error?) in
            if succeed {
                let user = AVUser.current()
                user.setObject(file, forKey: "avatar")
                user.saveInBackground({ (succeed: Bool, error: Error?) in
                    if succeed {
                        SVProgressHUD.showSuccess(withStatus: "上传成功")
                        AVAnalytics.event("上传头像成功")
                        self.imagePickerController = nil
                        self.tableView.reloadData()
                    } else {
                        if error != nil {
                            SVProgressHUD.showError(withStatus: error?.localizedDescription)
                        }
                    }
                })
                
            } else {
                if error != nil {
                    SVProgressHUD.showError(withStatus: error?.localizedDescription)
                }
            }
        })
    }
    
    // MARK: UIImagePickerControllerDelegate
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        updateAvatar(image)
        picker.dismiss(animated: true) {}
        UIApplication.shared.setStatusBarStyle(.lightContent, animated: true)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true) {}
    }
    
}
